package com.pan.handle.req.impl;

import com.pan.entity.HumbleHttpRequest;
import com.pan.handle.req.RequestHandle;
import com.pan.handle.req.strategy.xxx.Strategy;
import com.pan.handle.req.strategy.xxx.impl.BodyHandleStrategy;
import com.pan.handle.req.strategy.xxx.impl.CommonStrategy;
import com.pan.handle.req.strategy.xxx.impl.FirstLineStrategy;
import com.pan.handle.req.strategy.xxx.impl.HeaderStrategy;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

@Deprecated
public class HumbleHttpReqHandle2 implements RequestHandle<HumbleHttpRequest> {
//Multiple thread share this class instance, So this class shouldn't include status

    @Override
    public HumbleHttpRequest receive(Socket socket) {
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //current index of the strategy
        int cios = 0;
        HumbleHttpRequest request = new HumbleHttpRequest();
        byte data;

        CommonStrategy[] strategies;
        //The Strategy is status
        strategies = new CommonStrategy[]{
                new FirstLineStrategy(),
                new HeaderStrategy(),
                new BodyHandleStrategy(request)
        };
        Strategy currentStrategy = strategies[cios];
        while (true) {
            if (currentStrategy.isEnd()){
                if (currentStrategy.isComplete()){
                    currentStrategy.getResult(request);
                    cios++;
                    if (cios>=strategies.length){
                        return request;
                    }else {
                        currentStrategy = strategies[cios];
                    }
                }else {
                    //debug
                    System.out.println(this+"error: "+currentStrategy
                            +" end: This request doesn't meet requirements, Refuse to receive" +
                            "请求不符合要求，拒绝接收");
                    return null;
                }
            }
            try {
                data = (byte) inputStream.read();

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            currentStrategy.pushBuf(data);
        }
    }


}

